package com.common.library.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.common.library.R;
import com.common.library.net.HttpException;
import com.common.library.net.HttpQueue;
import com.common.library.net.HttpResponse;
import com.common.library.tools.JSONTools;
import com.common.library.ui.view.adapter.base.BaseRecyclerAdapter;
import com.common.library.ui.view.ptr.PtrDefaultLayout;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.yolanda.nohttp.error.NetworkError;
import com.yolanda.nohttp.error.TimeoutError;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;

import java.util.List;

/**
 * @author txf
 * @Title
 * @package com.txf.prevention.ui.fragment
 * @date 2017/5/5 0005
 */
public abstract class BaseRecyclerFragment<T> extends BaseFragment implements OnResponseListener<String> {
    private RelativeLayout mTitleLayout;
    private TextView mTitle;
    private TextView mSearch;

    private PtrDefaultLayout mPtrFrame;
    private RecyclerView mRecyclerView;
    private BaseRecyclerAdapter<T> mAdapter;
    private RecyclerAdapterWithHF mRecyclerAdapterWithHF;
    private RecyclerView.ItemDecoration mItemDecoration;

    private int mColumnCount = 1;//列数
    protected GridLayoutManager mManager;
    protected int pageIndex = 1;//页码
    protected int pageSize = 24;//每页条数
    protected long pageTime;// onResume 页面上次刷新时间
    protected long pageRefreshInterval = 60000000;// onResume 页面刷新间隔


    @Override
    protected View buildChildView() {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_base_recycler, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initView(view);
        init();
    }

    private void initView(View view) {
        mTitleLayout = (RelativeLayout) view.findViewById(R.id.fragment_base_title_layout);
        mTitle = (TextView) view.findViewById(R.id.fragment_base_title);
        mSearch = (TextView) view.findViewById(R.id.fragment_base_search);

        mPtrFrame = (PtrDefaultLayout) view.findViewById(R.id.base_recycler_PtrClassicFrameLayout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.base_recycler_RecyclerView);
    }

    private void init() {
        mRecyclerView.setLayoutManager(mManager = new GridLayoutManager(getContext(), mColumnCount));
        mRecyclerView.setAdapter(mRecyclerAdapterWithHF = new RecyclerAdapterWithHF(mAdapter));
        mManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (mRecyclerAdapterWithHF.getItemViewType(position)) {
                    case RecyclerAdapterWithHF.TYPE_HEADER://头
                    case RecyclerAdapterWithHF.TYPE_FOOTER://尾
                        return mColumnCount;
                    default:
                        return getManagerSpanSize(position);
                }
            }
        });
        if (mItemDecoration != null)
            mRecyclerView.addItemDecoration(mItemDecoration);
        //水平移动时禁用
//        mPtrFrame.disableWhenHorizontalMove(true);
        //下拉监听
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mPtrFrame.setLoadMoreEnable(false);
                pageIndex = 1;
                request(pageIndex);
            }
        });
        //上拉监听
        mPtrFrame.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                pageIndex++;
                request(pageIndex);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (System.currentTimeMillis() - pageTime > pageRefreshInterval) {
            pageTime = System.currentTimeMillis();
            mPtrFrame.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自动刷新
                    mPtrFrame.autoRefresh();
                }
            }, 100);
        }
    }

    protected abstract void request(int pageIndex);

    public void refreshData(List<T> datas) {
        if (pageIndex == 1) {
            if (datas != null)
                mAdapter.setDatas(datas);
            mPtrFrame.refreshComplete();
        } else {
            if (datas != null)
                mAdapter.addDatas(datas);
            mPtrFrame.loadMoreComplete(true);
        }
        if (datas != null)
            mAdapter.notifyDataSetChanged();
    }

    public void setAdapter(BaseRecyclerAdapter<T> mAdapter) {
        this.mAdapter = mAdapter;
    }

    public void setItemDecoration(RecyclerView.ItemDecoration mItemDecoration) {
        this.mItemDecoration = mItemDecoration;
    }

    public void setColumnCount(int mColumnCount) {
        this.mColumnCount = mColumnCount;
    }

    public PtrDefaultLayout getmPtrFrame() {
        return mPtrFrame;
    }

    public TextView getmTitle() {
        return mTitle;
    }

    public RelativeLayout getmTitleLayout() {
        return mTitleLayout;
    }

    public TextView getmSearch() {
        return mSearch;
    }

    public void setTitle(String data) {
        mTitle.setText(data);
    }

    public int getManagerSpanSize(int position) {
        return 1;
    }

    @Override
    public void onStop() {
        super.onStop();
        //页面关闭时，取消请求及相关动画
        HttpQueue.newHttpQueue().cancelRequest(TAG);
        if (mPtrFrame.isRefreshing()) {
            mPtrFrame.refreshComplete();
        } else if (mPtrFrame.isLoadingMore()) {
            mPtrFrame.loadMoreComplete(true);
        }
    }

    /////////////////////////////////////////////////////////////////////
    //////////////////////////////网络请求回执///////////////////////////
    /////////////////////////////////////////////////////////////////////
    @Override
    public void onStart(int what) {
    }

    @Deprecated
    @Override
    public void onSucceed(int what, Response<String> response) {
        Log.i(TAG, "--->UN 请求结果数据:");
        Log.i(TAG, response.get().toString());
        String strDecode = response.get().toString();
        HttpResponse result = JSONTools.fromJson(strDecode, HttpResponse.class);
        //无效数据过滤掉。
        if (result == null) {
            onError(what, HttpException.NONE_RESULT.getCode(), HttpException.NONE_RESULT.getMessage());
            return;
        }
        //服务器返回的错误信息在2000以后
        int error = Integer.parseInt(result.getErrCode());
        if (error != 0) {
            onError(what, error, result.getMsg());
            return;
        }
        onSuccess(what, new JsonParser().parse(strDecode), result.getMsg());
    }

    /**
     * 错误响应时
     *
     * @param what     多个请求时。该字段用于区别
     * @param response failure callback.
     */
    @Deprecated
    @Override
    public void onFailed(int what, Response<String> response) {
        response.getException().printStackTrace();
        if (response.getException() instanceof TimeoutError) {
            onError(what, HttpException.DEFAULT.getCode(), "请求超时");
        } else if (response.getException() instanceof NetworkError) {
            onError(what, HttpException.DEFAULT.getCode(), "网络异常");
        } else {
            onError(what, HttpException.DEFAULT.getCode(), HttpException.NONE_RESULT.getMessage());
        }
    }

    public void onSuccess(int what, JsonElement data, String message) {
    }

    public void onError(int what, int error, String message) {
    }

    @Override
    public void onFinish(int what) {
    }
}
